package cn.shanke.torrentmanagerserver.controller;

import cn.shanke.torrentmanagerserver.controller.common.ResponseModel;
import cn.shanke.torrentmanagerserver.model.Config;
import cn.shanke.torrentmanagerserver.service.ConfigService;
import cn.shanke.torrentmanagerserver.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Field;

@RestController
@RequestMapping("/config")
public class ConfigController {
    @Resource
    private ConfigService modelService;

    @GetMapping("/get")
    public ResponseModel getProperties(@RequestParam(value = "properties[]",required = false) String[] properties) {
        Config config = modelService.getCurrent();
        if (properties != null && properties.length > 0) {
            JSONObject data = new JSONObject();
            for (String property : properties) {
                try {
                    Field field = Config.class.getDeclaredField(property);
                    field.setAccessible(true);
                    data.put(property, field.get(config));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
            }
            return ResponseModel.success().data(data);
        }
        return ResponseModel.success().data(config);
    }

    @PostMapping("/set")
    public ResponseModel set(@RequestBody JSONObject req) {
        Config config = modelService.getCurrent();
        String libraryPath = req.getString("libraryPath");
        if (libraryPath != null) {
            config.setLibraryPath(libraryPath);
        }

        String managePathHost = req.getString("managePathHost");
        if (managePathHost != null) {
            config.setManagePathHost(StringUtil.removeLastSlash(managePathHost));
        }
        modelService.updateById(config);
        return ResponseModel.success().data(config);
    }

}
